<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <a href="/">首页</a>
  <a href="/user">用户</a>
  <a href="/pro">产品</a>
  <div id="content">
    首页
  </div>
</body>
<script>
  var router = {
    // 存储路由的对象
    routes: {},
    // 定义路由的方法
    route(path, callback) {
      this.routes[path] = callback
    },
    // 用于触发指定的路由操作
    go(path) {
      /*
       *  更改url,
       * param1:与路径有关的数据,
       * param2:null或者字符串,
       * params3:将浏览器地址修改为什么地址 
      **/
      history.pushState({ path: path}, null, path)
      //触发路由对应的回调函数
      this.routes[path] && this.routes[path]()
    },
    init(){
      var that = this
      window.addEventListener('popstate', function(e) {
        var path = e.state ? e.state.path : ''
        that.routes[path] && that.routes[path]()
      })
    }
  }

  //设置a标签的功能
  var links = document.querySelectorAll("a")

  links.forEach(function (ele) {
    ele.addEventListener('click', function (event) {
      router.go(this.getAttribute("href"))
      console.log(123)
      event.preventDefault()
    })
  })

  var content = document.getElementById("content");

  router.route('/', function () {
    content.innerHTML = '首页';
  })
  router.route('/user', function () {
    content.innerHTML = '用户';
  })
  router.route('/pro', function () {
    content.innerHTML = '产品';
  })

  router.init()
</script>

</html>